package com.example.dao;


import com.example.pojo.Picture;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ControllerAdvice;
import utils.PaginationHelper;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Repository
@ControllerAdvice
public class PictureDao extends JdbcDaoSupport {

    public PaginationHelper getPictures (String userCode, int page, int pageSize) {
        String sql = "SELECT * FROM pl_picture WHERE user_code=?";
        return new PaginationHelper(sql, new Object[]{userCode}, page, pageSize, super.getJdbcTemplate());
    }

    public boolean putPicture (final Picture picture) {
        String sql = "INSERT INTO pl_picture(user_code, pt_url, pt_description, pt_time) VALUE (?, ?, ?, ?)";
        int success = super.getJdbcTemplate().update(sql,
                new PreparedStatementSetter() {
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        preparedStatement.setString(1, picture.getUserCode());
                        preparedStatement.setString(2, picture.getPictureUrl());
                        preparedStatement.setString(3, picture.getPictureDescription());
                        preparedStatement.setInt(4, picture.getTime());
                    }
                });
        return success >= 1;
    }

    @Resource
    public void setJb (JdbcTemplate jdbcTemplate) {
        super.setJdbcTemplate(jdbcTemplate);
    }
}
